package com.whut.controller;

import com.alibaba.fastjson.JSON;
import com.whut.mapper.ContracttaskprojectMapper;
import com.whut.model.*;
import com.whut.service.CheckInfoService;
import com.whut.service.ReportService;
import com.whut.utils.FileUtil;
import com.whut.utils.HttpUtil;
import com.whut.utils.MDoc;
import com.whut.v_model.PCDandUSERNAME;
import com.whut.v_vo.*;
import freemarker.template.TemplateException;
import org.apache.http.client.ClientProtocolException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;


@Controller
@RequestMapping("/checkInfo")
public class CheckInfoController {

    @Resource
    private CheckInfoService checkInfoService;
    @Resource
    private ReportService reportService;
    @Resource
    private ContracttaskprojectMapper contracttaskprojectMapper;

    @ResponseBody
    @PostMapping("/getCheck")
    public Object getCheckInfoByPage(String startTime, String endTime, int curPage, int pageSize,
                                     String checkState, String startTimeY, String endTimeY, int client,String projectName) {
          return checkInfoService.getCheckInfoByPage(startTime, endTime, curPage, pageSize, checkState, startTimeY, endTimeY, client,projectName);
    }
    @ResponseBody
    @PostMapping("/getIsNew")
    public boolean getIsNew(int checkId){
        return checkInfoService.getIsNew(checkId);
    }

    @ResponseBody
    @PostMapping("/fyTest")
    public String test(String id) throws UnsupportedEncodingException {
        System.out.println(id);
        return checkInfoService.test();
    }

    @ResponseBody
    @PostMapping("/test")
    public Object getTest(Integer equipId) {

        return checkInfoService.getTest(equipId);
    }

    /**
     * 通过报告类型选择，生成不同报告，返回报告url到前台进行网络传输下载
     *
     * @param projectId, checkId, reportType]
     * @return java.lang.String
     * @author fanyu
     * @date 2019/8/23 13:59
     */
    @ResponseBody
    @PostMapping("/report")
    public String generateReport(int projectId, int checkId, int reportType,boolean isNew) throws UnsupportedEncodingException,Exception{
        return generateReportFunc(projectId,checkId,reportType,isNew);
    }

    /**
     * @author: liukang
     * @Description: 报告预览
     * @date: 2020/9/9 15:04
     * @param:
     * @return:
     */
    @ResponseBody
    @PostMapping("/previewReport")
    public String previewReport(int projectId, int checkId, int reportType,boolean isNew) throws UnsupportedEncodingException,Exception{
        String res = generateReportFunc(projectId,checkId,reportType,isNew);
        return res;
    }

    /**
     * @author: liukang
     * @Description: 生成报告的方法，解耦出来
     * @date: 2020/9/9 14:45
     * @param:
     * @return:
     */
    private String generateReportFunc(int projectId, int checkId, int reportType,boolean isNew) throws UnsupportedEncodingException,Exception{
        String result = "";
        if (reportType == 1 || reportType == 2) {
            result = checkInfoService.generateCheckReport(projectId, checkId, reportType);
        } else if (reportType == 3) {
            result = checkInfoService.generateReportType3(projectId, checkId);
        } else if (reportType == 4) {
            //LK  中建三局质量专项报告
            result = checkInfoService.generateReportType4(projectId, checkId);
        } else if (reportType == 5) {
            result = reportService.rectificationNoticeCreate(checkId);
        } else if (reportType == 6) {
            result = reportService.patrolReport(checkId);
        } else if (reportType == 7) {
            result = reportService.supervisionSpotCheckOfSgseftyInJsproject(checkId);
        }else if(reportType==8||reportType==9) {
            //  香港置地安全报告/质量报告
            result=reportService.getMXTQreport(checkId,projectId,reportType);
        }else if(reportType==10) {
            //  可视化安全报告
            result=reportService.getVisualizationReport(checkId,projectId);
        }else if(reportType==11) {
            result=reportService.getVisualizationReport2(checkId,projectId);
        }else if(reportType==12){
            //建设局综合检查报告
            result = reportService.constructionMulCheckReport(checkId, projectId,isNew);
        }else if(reportType==13){
            result = reportService.cityEquipAssessReport(checkId,projectId,8255);
        }else if(reportType==14){
            result = reportService.houseEquipAssessReport(checkId,projectId,8256);
        } else if(reportType == 15){
            result = reportService.equipReport(checkId, projectId);
        } else if(reportType == 16){
            result = reportService.comperhensiveInspectionReport(checkId, projectId);
        } else if(reportType == 17){
            result = checkInfoService.newHiddenCheckReport(projectId, checkId);
        }
        else if(reportType == 18){
            result = reportService.generate3rdPartyRiskReport(projectId, checkId);
        }
        return result;
    }



    @ResponseBody
    @PostMapping("/getChooseInfo")
    public List<Object> getChooseReport(int checkId) {
        System.out.println(JSON.toJSON(checkInfoService.getChooseInfo(checkId)));
        return checkInfoService.getChooseInfo(checkId);
    }

    @ResponseBody
    @PostMapping("/getNewChooseInfo")
    public List<Object> getNewChooseReport(int checkId) {
        return checkInfoService.getNewChooseInfo(checkId);
    }

    @ResponseBody
    @PostMapping("/getFourthInfo")
    public List<? extends Object> getFourthInfo(String checkId, String fourthId) {
        return checkInfoService.getFourthInfo(Integer.parseInt(checkId), Integer.parseInt(fourthId));
    }

    @ResponseBody
    @PostMapping("/getContractInfo")
    public Object getContractInfo(int curPage, int pageSize) {
        return checkInfoService.getContractInfoByPage(curPage, pageSize);
    }

    /*
     * @Author wenyihan
     * @Description vague search
     * @Date 9:36 2019/6/20
     * @Param [curPage, pageSize, inputSearch]
     * @return java.lang.Object
     **/
    @ResponseBody
    @PostMapping("/searchContractInfo")
    public Object searchContractInfo(int curPage, int pageSize, String inputSearch) {
        return checkInfoService.searchContractInfoByPage(curPage, pageSize, inputSearch);
    }

    @ResponseBody
    @PostMapping("/addContractInfo")
    public String addContractInfo(Contractinfo contractinfo) {
        return checkInfoService.addContractInfo(contractinfo);
    }

    @ResponseBody
    @PostMapping("/deleteContractInfo")
    public String deleteContractInfo(int contractId) {
        return checkInfoService.deleteContractInfo(contractId);
    }

    @ResponseBody
    @PostMapping("/addPointLimitInfo")
    public String addPointLimitInfo(Pointlimit pointlimit) {
        return checkInfoService.addPointLimitInfo(pointlimit);
    }

    @ResponseBody
    @PostMapping("/deletePointLimitInfo")
    public String deletePointLimitInfo(Integer mKey) {
        return checkInfoService.deletePointLimitInfo(mKey);
    }

    @ResponseBody
    @PostMapping("/editPointLimitInfo")
    public String editPointLimitInfo(Pointlimit pointlimit) {
//        System.out.println(pointlimit);
        return checkInfoService.editPointLimitInfo(pointlimit);
    }

    @ResponseBody
    @PostMapping("/getLimitPoint")
    public Object getLimitPoint(int curPage, int pageSize) {
        return checkInfoService.getLimitPoint(curPage, pageSize);
    }

    @ResponseBody
    @PostMapping("/deleteCheckInfo")
    public String deleteCheckInfo(int checkId) {
        return checkInfoService.deleteCheckInfo(checkId);
    }

    @ResponseBody
    @PostMapping("/saveCheckResultEdit")
    public String saveCheckResultEdit(int mkey,int fifthId,int sixthId, String riskPoint, String suggestion, String picName) {
        return checkInfoService.saveCheckResultEdit(mkey, fifthId,sixthId,riskPoint, suggestion, picName);
    }

    @ResponseBody
    @PostMapping("/saveBack")
    public String saveBack(int checkId) {
        return checkInfoService.saveBack(checkId);
    }

    @ResponseBody
    @PostMapping("/docxUpload")
    public String docxUpload(@RequestParam("file") MultipartFile file, @RequestParam("checkId") int checkId) {
        Date date = new Date();
        String time = new SimpleDateFormat("yyyyMMddHHmmss").format(date);
        System.out.println(time);
        String resultPath = null;
        try {
            resultPath = FileUtil.upload(file.getInputStream(), "docx/", time + file.getOriginalFilename());
            System.out.println(resultPath);
            return checkInfoService.uploadReport(checkId, time + file.getOriginalFilename());
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }

    @ResponseBody
    @PostMapping("/download")
    public String download(int checkId) {
        return checkInfoService.getDownLoadUrlByCheckId(checkId);
    }

    @ResponseBody
    @PostMapping("/deleteProblemCollect")
    public String deleteProblemCollect(int mkey) {
        return checkInfoService.deleteProblemCollect(mkey);
    }

    @ResponseBody
    @PostMapping("/getUncheckInfo")
    public Object getUncheckInfo(int fourthId, int checkId) {
        return checkInfoService.getUncheckInfo(fourthId, checkId);
    }

    @ResponseBody
    @PostMapping("/picTest")
    public Object getJFreeChart() throws ClientProtocolException, IOException, TemplateException,UnsupportedEncodingException {
        Object[] data0=new Object[]{0.1,0.2,0.3,0.4,0.5};
        Object[] data1=new Object[]{0.1,"","","",""};
        Object[] data2=new Object[]{"",0.2,"","",""};
        Object[] data3=new Object[]{"","",0.3,"",""};
        Object[] data4=new Object[]{"","","",0.4,""};
        Object[] data5=new Object[]{"","","","",0.5};
        Object[] data6=new Object[]{"","","","",""};
        HashMap<String,String> map=new HashMap<>();
        HashMap<String,Object> dataSet=new HashMap<>();
        dataSet.put("data0",data0);
        dataSet.put("data1",data1);
        dataSet.put("data2",data2);
        dataSet.put("data3",data3);
        dataSet.put("data4",data4);
        dataSet.put("data5",data5);
        dataSet.put("data6",data6);
        map.put("dataSet",JSON.toJSONString(dataSet));
        map.put("height","468");
        map.put("width","718");
        map.put("index","5");
        //map1.put("options",option);


        //String base64= HttpUtil.post("http://10.138.115.72:3000/echarts",map,"utf-8");
        //System.out.println(base64);
        Map<String, Object> dataMap = new HashMap<String, Object>();
        List<Object> list=new ArrayList<>();
        for(int i=0;i<1;i++)
        {
            String base64= HttpUtil.post("http://10.138.116.179:3000/jsmind",map,"utf-8");
            Map<String,Object> map1=new HashMap<>();
            map1.put("pic1",base64.substring(22));
            list.add(map1);
        }
        dataMap.put("picList",list);
        MDoc mdoc = new MDoc();
        mdoc.createDoc(dataMap, "D:\\WYH.doc", "ftl\\test111.ftl");
        String result = "D:\\heihei.doc";
        System.out.println("成功生成模板");
        return null;
    }

    //根据类别查询委托方
    @ResponseBody
    @PostMapping("/getClientByType")
    @CrossOrigin("*")
    public List<Object> getClientByType(String clientType) {
        return checkInfoService.getClientByType(clientType);
    }

    @ResponseBody
    @PostMapping("/fix")
    public Object fix() {
        List<ContractTaskProject> contracttaskprojectList=contracttaskprojectMapper.selectAllFixInfo();
        for(int i=0;i<contracttaskprojectList.size();i++)
        {
            contracttaskprojectList.get(i).setTaskId(contracttaskprojectMapper.getFixTaskIdByProjectId(contracttaskprojectList.get(i).getProjectId()));
            contracttaskprojectMapper.updateByPrimaryKeySelective(contracttaskprojectList.get(i));
        }
        return "success";
    }

    /**
     * @author： wenyihan
     * @description：查询检查下对应的所有已被组长审核的问题
     * @date： 17:48 2020/9/10
     * @param： [checkId]
     * @return： java.util.List<java.lang.Object>
    */
    @ResponseBody
    @PostMapping("/findAllInfo")
    public List<Object> findAllInfo(Integer checkId){
        return checkInfoService.findAllInfo(checkId);
    }

    /**
     * @author： wenyihan
     * @description：问题审核
     * @date： 18:06 2020/9/11
     * @param： [checkId]
     * @return： java.lang.Object
    */
    @ResponseBody
    @PostMapping("/examineProblem")
    public Object examineProblem(Integer checkId){
        return checkInfoService.examineProblem(checkId);
    }

    /**
     * @author： wenyihan
     * @description：判断改问题是否经过最终审核
     * @date： 20:03 2020/9/11
     * @param： [checkId]
     * @return： java.lang.Object
    */
    @ResponseBody
    @PostMapping("/qualifyExamine")
    public Object qualifyExamine(Integer checkId){
        return checkInfoService.qualifyExamine(checkId);
    }


    //返回examineInfo中第二级collapse中显示的第四级名称
     @ResponseBody
     @PostMapping("/getnode4nameBycheckId")
     public List<Node4PName1VO> Getnode4nameBycheckId(Integer checkId) {
         return checkInfoService.Getnode4nameBycheckId(checkId);
     }

     //返回examineInfo中table的信息，包括PCD表和检查人（userName）
    @ResponseBody
    @PostMapping("/findPCDInfo")
    public List<PCDandUSERNAME> findPCDInfo(Integer checkId, Integer fourthId){
        return checkInfoService.findPCDInfo(checkId, fourthId);
    }

    /**
     * @author： wenyihan
     * @description：获取问题项小结
     * @date： 16:15 2020/10/13
     * @param： [checkId, fourthId]
     * @return： java.util.List<java.lang.Summary>
    */
    @ResponseBody
    @PostMapping("/getSummary")
    public List<Summary> getSummary(Integer checkId, Integer fourthId){
        return checkInfoService.getSummary(checkId,fourthId);
    }

    /**
     * @author： wenyihan
     * @description：通过第四级id获取所有对应的第六级id
     * @date： 18:50 2020/10/27
     * @param： [fourthId]
     * @return： java.util.List<java.lang.String>
    */
    @ResponseBody
    @PostMapping("/findSixthName")
    public List<Prefixsystem> findSixthName(Integer fourthId){
        return checkInfoService.findSixthName(fourthId);
    }

    /**
     * @author： wenyihan
     * @description：通过第六级id获取所有对应的问题描述
     * @date： 16:21 2020/10/28
     * @param： [sixthId]
     * @return： java.util.List<com.whut.model.Problemdescription>
    */
    @ResponseBody
    @PostMapping("/findProblemDesBySixthId")
    public List<Newproblemdescription> findProblemDesBySixthId(Integer sixthId){
        return checkInfoService.findProblemDesBySixthId(sixthId);
    }

    /**
     * @author： wenyihan
     * @description：根据最后一级id获取问题描述对应的问题数量（性质）
     * @date： 11:03 2020/11/1
     * @param： [lastId]
     * @return： java.util.Map<java.lang.Integer,java.lang.String>
    */
    @ResponseBody
    @PostMapping("/findProblemNumByLastId")
    public List<ProblemNumVO> findProblemNumByLastId(Integer lastId){
        return checkInfoService.findProblemNumByLastId(lastId);
    }

    /**
     * @author： wenyihan
     * @description：审核界面点击修改按钮后，problemCollect表中对应字段修改
     * @date： 10:36 2020/10/30
     * @param： [mkey, fifthId, sixthId, remark, suggestion, picName, checkPart, lastId]
     * @return： boolean
    */
    @ResponseBody
    @PostMapping("/problemCollectUpdate")
    public boolean problemCollectUpdate(Integer mkey, Integer fifthId, Integer sixthId, String remark, String suggestion, String problemQua, String picName, String checkPart, Integer lastId){
        return checkInfoService.problemCollectUpdate(mkey, fifthId, sixthId, remark, suggestion, problemQua, picName,checkPart, lastId);
    }

    /**
     * @author： wenyihan
     * @description：审核界面点击修改按钮后，newProblemDespriction表中对应字段修改
     * @date： 11:38 2020/10/30
     * @param： [number, riskNumber]
     * @return： boolean
    */
    @ResponseBody
    @PostMapping("/newProblemDesUpdate")
    public boolean newProblemDesUpdate(Integer number,String riskNumber){
        return checkInfoService.newProblemDesUpdate(number, riskNumber);
    }

    /**
     * @author： wenyihan
     * @description：审核界面点击修改按钮后，对corrspondScale字段修改，涉及pc，npd以及rsc表
     * @date： 11:45 2020/10/30
     * @param： [meky, lastId]
     * @return： boolean
    */
    @ResponseBody
    @PostMapping("/corrspondScaleUpdate")
    public boolean corrspondScaleUpdate(Integer mkey, Integer lastId, String correspondScale){
        return checkInfoService.corrspondScaleUpdate(mkey, lastId, correspondScale);
    }

    /**
     * @author： wenyihan
     * @description：编辑后对更新数据查询
     * @date： 11:14 2020/11/10
     * @param： [checkId, fourthId]
     * @return： java.util.List<com.whut.v_model.PCDandUSERNAME>
    */
    @ResponseBody
    @PostMapping("/findPCDInfoAfterUpdate")
    public List<PCDandUSERNAME> findPCDInfoAfterUpdate(Integer checkId, Integer fourthId){
        return checkInfoService.findPCDInfoAfterUpdate(checkId, fourthId);
//        return null;
    }

    @ResponseBody
    @RequestMapping("/saveEditInfo")
    public String saveEditInfo(int mkey,String riskPoint,String suggestion,String picName){
        return checkInfoService.saveEditInfo(mkey,riskPoint,suggestion,picName);
    }

    /**
     * @author： wenyihan
     * @description：判断项目新老体系
     * @date： 18:31 2020/12/13
     * @param： [checkId]
     * @return： java.lang.Boolean
    */
    @ResponseBody
    @PostMapping("/judgeNewOrOldSystem")
    public Boolean judgeNewOrOldSystem(int checkId){
        return checkInfoService.judgeNewOrOldSystem(checkId);
    }

    /**
     * @author： wenyihan
     * @description：在老系统中通过上级id获取下级名称+number
     * @date： 22:51 2020/12/15
     * @param： [perNum]
     * @return： java.util.List<com.whut.v_vo.oldSysPreListVO>
    */
    @ResponseBody
    @PostMapping("/getpNameByUpperIdInOldSys")
    public List<oldSysPreListVO> getpNameByUpperId(int preNum){
        return checkInfoService.getpNameByUpperId(preNum);
    }

    /**
     * @author： wenyihan
     * @description：在老系统中通过上级id找到最后一级的pd，np，pn
     * @date： 12:58 2020/12/17
     * @param： [preNum]
     * @return： java.util.List<com.whut.v_vo.oldSysLastListVO>
    */
    @ResponseBody
    @PostMapping("/getLastListByUpperIdInOldSys")
    public List<oldSysLastListVO> getLastListByUpperId(int preNum){
        return checkInfoService.getLastListByUpperId(preNum);
    }

    /**
     * @author： wenyihan
     * @description：老体系修改更新
     * @date： 19:59 2020/12/17
     * @param： [mKey, fifthId, sixthId, lastId, problemQua, suggestion, pic, riskPoint]
     * @return： java.lang.Boolean
    */
    @ResponseBody
    @PostMapping("/oldSysUpdate")
    public Boolean oldSysUpdate(Integer mKey, Integer fifthId, Integer sixthId, Integer lastId, String problemQua, String suggestion, String pic, String riskPoint){
        return checkInfoService.oldSysUpdate(mKey, fifthId, sixthId, lastId, problemQua, suggestion, pic, riskPoint);
    }

    /**
     * @author： wenyihan
     * @description：根据选择的problemQua得到当前riskPoint
     * @date： 19:57 2020/12/17
     * @param： [lastId, problemQua]
     * @return： java.lang.String
    */
    @ResponseBody
    @PostMapping("/calculateRiskPoint")
    public String calculateRiskPoint(Integer lastId, String problemQua){
        return checkInfoService.calculateRiskPoint(lastId, problemQua);
    }

    /**
     * @author： wenyihan
     * @description：编辑小结
     * @date： 21:28 2020/12/17
     * @param： [summary]
     * @return： java.lang.String
    */
    @ResponseBody
    @PostMapping("/editSummary")
    public String editSummary(Integer mKey, String summary){
        return checkInfoService.editSummary(mKey, summary);
    }

    /**
     * @author： wenyihan
     * @description：如果没有小结，则插入小结
     * @date： 21:57 2020/12/17
     * @param： [checkId, fourthId, summary, firstId]
     * @return： java.lang.String
    */
    @ResponseBody
    @PostMapping("/insertSummary")
    public String insertSummary(Integer checkId, Integer fourthId, String summary, Integer firstId){
        return checkInfoService.insertSummary(checkId, fourthId, summary, firstId);
    }

    /**
     * @author： wenyihan
     * @description：获取老体系第四级信息
     * @date： 19:35 2020/12/23
     * @param： [checkId, fourthId]
     * @return： java.util.List<com.whut.v_vo.oldSysExamInfoVO>
    */
    @ResponseBody
    @PostMapping("/getOldSysFourthInfo")
    public List<oldSysExamInfoVO> getOldSysFourthInfo(Integer checkId, Integer fourthId){
        return checkInfoService.getOldSysFourthInfo(checkId, fourthId);
    }



}